package com.tdam2011.grupo02.ui;

import java.util.LinkedList;

import com.tdam2011.grupo02.R;
import com.tdam2011.grupo02.domain.SMS;
import com.tdam2011.grupo02.data.LogsController;
import com.tdam2011.grupo02.widget.popup.ActionItem;
import com.tdam2011.grupo02.widget.popup.QuickAction;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

public class SmsLogListFragment extends ListFragment implements
		OnClickDialogFragmentInterface {

	private static Context context;
	private SmsAdapter smsAdapter;
	private ListView smsListView;
	private int adapterPosition;
	private QuickAction smsPopup;
	private SmsAsyncTask smsAsyncTask;
	private LogsController controller;
	private SMS sms;

	private final static int POPUP_ACTION_ITEM_DELETE = 12;

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		setListShown(true);

		smsListView = getListView();

		smsAdapter = new SmsAdapter();
		smsListView.setAdapter(smsAdapter);
		smsListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				SMS aux = (SMS) smsAdapter.getItem(position);
				Intent r = new Intent(context, SmsConversationActivity.class);
				r.putExtra("threadId", aux.getThreadId());
				r.putExtra("name", aux.getNombre());
				r.putExtra("number", aux.getNumero());
				r.putExtra("imgUri", aux.getImageUri());
				startActivity(r);
			}
		});

		smsListView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {

				adapterPosition = position;

				int firstPosition = getListView().getFirstVisiblePosition()
						- getListView().getHeaderViewsCount();
				int wantedChild = adapterPosition - firstPosition;

				View v = (View) smsListView.getChildAt(wantedChild);

				smsPopup.show(v);
				return false;
			}
		});

		controller = new LogsController(context);

		createSmsPopup();
	}

	@Override
	public void onResume() {
		initSmsData();
		super.onResume();
	}

	private void initSmsData() {
		ContactDataInterface data = (ContactDataInterface) context;
		String nombreContacto = data.onDataSelected()[1];

		smsAsyncTask = new SmsAsyncTask();
		smsAsyncTask.execute(nombreContacto);
	}

	public void createSmsPopup() {
		ActionItem eliminarItem = new ActionItem(POPUP_ACTION_ITEM_DELETE,
				getString(R.string.actionDelete), getResources().getDrawable(
						android.R.drawable.ic_menu_delete));

		smsPopup = new QuickAction(context);

		smsPopup.addActionItem(eliminarItem);
		smsPopup.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
			@Override
			public void onItemClick(QuickAction quickAction, int pos,
					int actionId) {
				sms = (SMS) smsAdapter.getItem(adapterPosition);
				if (actionId == POPUP_ACTION_ITEM_DELETE) {
					showDialog();
				}
			}
		});

		smsPopup.setOnDismissListener(new QuickAction.OnDismissListener() {
			@Override
			public void onDismiss() {
			}
		});

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = getActivity();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		inflater.inflate(R.layout.log_sms, container);
		return super.onCreateView(inflater, container, savedInstanceState);
	}

	// REGISTRO DE SMS

	/*
	 * public void orderSms(int order) { Comparator<SMS> comparator = null;
	 * 
	 * switch (order) { case ORDER_SMS_CONTACT_ASC: comparator = new
	 * SortSMSByContactAsc(); break; case ORDER_SMS_CONTACT_DESC: comparator =
	 * new SortSMSByContactDesc(); break; case ORDER_SMS_DATE_ASC: comparator =
	 * new SortSMSByDateAsc(); break; case ORDER_SMS_DATE_DESC: comparator = new
	 * SortSMSByDateDesc(); break; }
	 * 
	 * Collections.sort(smsData, comparator); }
	 */
	private class SmsAsyncTask extends
			AsyncTask<String, LinkedList<SMS>, LinkedList<SMS>> {

		@Override
		protected LinkedList<SMS> doInBackground(String... params) {
			return controller.getFirstSMSConversations(params[0]);
		}

		@Override
		protected void onPostExecute(LinkedList<SMS> result) {
			smsAdapter.add(result);
			smsAdapter.notifyDataSetChanged();

			super.onPostExecute(result);
		}

	}

	private class SmsAdapter extends BaseAdapter {
		private LinkedList<SMS> sms;
		private LayoutInflater inflater;

		public SmsAdapter() {
			this.sms = new LinkedList<SMS>();
			inflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return sms.size();
		}

		@Override
		public Object getItem(int position) {
			return sms.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		public void add(LinkedList<SMS> sms) {
			if (sms != null)
				this.sms = sms;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup arg2) {
			Holder holder;
			final SMS info = (SMS) getItem(position);

			if (convertView == null) {
				convertView = inflater.inflate(
						R.layout.item_all_conversation_sms, null);
				holder = new Holder();

				holder.img = (ImageView) convertView
						.findViewById(R.id.imgContacto);
				holder.emisor = (TextView) convertView
						.findViewById(R.id.emisor);
				holder.mensaje = (TextView) convertView
						.findViewById(R.id.mensaje);

				convertView.setTag(holder);
			} else {
				holder = (Holder) convertView.getTag();
			}

			holder.img.setImageURI(info.getImageUri());
			holder.emisor.setText(info.getNombre() + "\n"
					+ info.getFecha().toLocaleString());
			holder.mensaje.setText(info.getMensaje());

			return convertView;
		}

		class Holder {
			private ImageView img;
			private TextView emisor;
			private TextView mensaje;
		}
	}

	// Dialog Fragment

	private void showDialog() {
		DialogFragment newFragment = MyAlertDialogFragment.newInstance(this,
				getString(R.string.attentionAlertDialogTitle),
				getString(R.string.deleteItemAlertDialogMessage));
		newFragment.show(getFragmentManager(), "dialog");
	}

	@Override
	public void doPositiveClick() {
		int num = controller.deleteSmsConversationLog(sms.getThreadId());
		Log.d("DEMO", "cant = " + num);
		if (num != 0)
			initSmsData();
	}

	@Override
	public void doNegativeClick() {
		// TODO Auto-generated method stub
		
	}
}